package com.example.handler;

import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.mall.Product;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;

/**
 * @ClassName GlobalExceptionHandler
 * @Description TODO
 * @Author: XMK
 * @Date: 2020/4/29 10:08
 * @Version: 1.0
 */
public class GlobalExceptionHandler {

    public static SentinelClientHttpResponse handleBlock(HttpRequest request,
                                                         byte[] body, ClientHttpRequestExecution execution,
                                                         BlockException ex) {
        Product product = new Product();
        product.setProductName("限流产品");
        product.setId(0L);

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            return new SentinelClientHttpResponse(objectMapper.writeValueAsString(product));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static SentinelClientHttpResponse handleFallback(HttpRequest request,
                                                         byte[] body, ClientHttpRequestExecution execution,
                                                         BlockException ex) {
        Product product = new Product();
        product.setProductName("降级产品");
        product.setId(0L);

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            return new SentinelClientHttpResponse(objectMapper.writeValueAsString(product));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
